package xyz.weblade.lynchmybatis;

import ognl.DefaultClassResolver;
import ognl.MemberAccess;
import ognl.Ognl;
import ognl.OgnlException;

import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lynch
 * @since 2025/6/13 v1.0
 */
public class TestOgnl {

    // 自定义 MemberAccess 实现
    private static final MemberAccess MEMBER_ACCESS = new MemberAccess() {
        public Object setup(Map context, Object target, Member member, String propertyName) {
            return null;
        }

        public void restore(Map context, Object target, Member member, String propertyName, Object state) {
        }

        public boolean isAccessible(Map context, Object target, Member member, String propertyName) {
            // 允许访问 public 成员
            return Modifier.isPublic(member.getModifiers());
        }
    };
    public static void main(String[] args) {
        Map<String, Object> innerMap = new HashMap<>();
        innerMap.put("userId", 10001);
        innerMap.put("username", "alice");

        Map<String, Object> filterMap = new HashMap<>();
        filterMap.put("minAge", "28282222222222222L");
        filterMap.put("maxAge", 30);

        Map<String, Object> rootMap = new HashMap<>();
        rootMap.put("user", innerMap);
        rootMap.put("filter", filterMap);
        rootMap.put("searchText", "java developer");

        Map context = Ognl.createDefaultContext(
                rootMap,
                MEMBER_ACCESS,      // 提供 MemberAccess 实现
                new DefaultClassResolver(),
                null
        );

        testOgnlExpression(context,rootMap, "filter.minAge == 28282222222222222L", "XXXX");

    }
    private static void testOgnlExpression(Map context, Object root,
                                           String expression,
                                           String description) {
        try {
            // 4. 使用自定义上下文执行 OGNL
            Object parsedExpression = Ognl.parseExpression(expression);
            Object value = Ognl.getValue(parsedExpression, context, root);

            System.out.printf("表达式: %-25s → 结果: %-20s (%s)%n",
                    "'" + expression + "'",
                    value,
                    description);
        } catch (OgnlException e) {
            System.err.println("解析表达式 '" + expression + "' 出错: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("执行表达式 '" + expression + "' 出错: " + e.getMessage());
        }
    }

}
